package com.cheung.leetcode.tree;

import lyroot.entity.TreeNode;
import org.junit.jupiter.api.Test;

import java.util.*;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.tree
 * @Author :  cheungming
 * @CreateTime : 2024-05-17 08:37:12
 * @Description : 二叉树自底向上层序遍历
 * @Version : 1.0
 */
public class Code107Test {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node != null) {
                    list.add(node.val);
                    if (node.left != null) {
                        queue.offer(node.left);
                    }
                    if (node.right != null) {
                        queue.offer(node.right);
                    }
                }


            }
            res.add(0, list);
        }

        return res;
    }

    @Test
    public void test1() {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);

        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        assert levelOrderBottom(root).equals(Arrays.asList(Arrays.asList(15, 7), Arrays.asList(9, 20), List.of(3)));
    }

    @Test
    public void test2() {
        TreeNode root = new TreeNode(1);
        assert levelOrderBottom(root).equals(List.of(List.of(1)));
    }

    @Test
    public void test3() {
        assert levelOrderBottom(null).isEmpty();
    }
}
